package redi

import (
	"time"

	"github.com/gogf/gf/frame/g"
)

// 添加Set对象
func SET_Add(key string, val string){
	g.Redis().DoVar("SADD", key, val)
}

// 删除Set的某个对象
func SET_Remove(key string, val string){
	g.Redis().DoVar("SREM", key, val)
}

// 得到Set的全部成员
func SET_getMembers(key string) []string {
	v, err := g.Redis().DoVar("SMEMBERS", key)
	if err != nil {
		return nil 
	}
	
	return v.Strings()
}


func HGetRedisAll(key string) map[string]interface{}{
	v, err := g.Redis().DoVar("HGETALL", key)
	if err != nil {
		return nil 
	}
	
	return v.MapStrAny()
}

func HGetRedisValue(key string, hkey string) string{
	v, err := g.Redis().DoVar("HGET", key, hkey)
	if err != nil {
		return "" 
	}
	return v.String()
}

func HSetRedisValue(key string, hkey string, hval string){
	HSetRedisValueExpire(key, hkey, hval, 60 * 60 * 24 * 2)
}

func HSetRedisValueExpire(key string, hkey string, hval string, expire int){
	g.Redis().DoVar("HSET", key, hkey, hval)
	g.Redis().Do("EXPIRE", key, expire)
}


// 获取缓存
func GetRedisValue(key string) (val string){
	v, err := g.Redis().DoVar("GET", key)
	if err != nil {
		return "" 
	}
	return v.String()
}

// 删除缓存
func DelRedisValue(key string)(err error){
	_, err = g.Redis().Do("EXPIRE", key, 1)
	return
}

func SetRedisValue(key, val string) (err error){
	return SetRedisValueExpire(key, val, 1)
}

// 缓存，失效时间timeout秒
func SetRedisValueExpire(key, val string, timeout int) (err error){
	_, err = g.Redis().DoVar("SET", key)
	g.Redis().Do("EXPIRE", key, timeout)
	return
}


// 缓存，失效时间到第二天0点
func SetRedisValueExpireToday(key, val string) (err error) {
	tomorrow := time.Now().AddDate(0,0,1).Format("2006-01-02")
	t, _ := time.ParseInLocation("2006-01-02", tomorrow, time.Local)
	timeout := int(t.Unix() - time.Now().Unix())
	return SetRedisValueExpire(key, val, timeout)
}